<?php

namespace app\admin\controller\mox\play;

use app\common\controller\Backend;
use think\Db;

/**
 * 木偶戏剧目管理
 *
 * @icon fa fa-circle-o
 */
class Info extends Backend
{

    /**
     * Info模型对象
     * @var \app\admin\model\mox\play\Info
     */
    protected $model = null;
    protected $multiFields = 'is_perform,is_represent';
    // protected $toggleFields = ['status', 'is_represent'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\mox\play\Info;
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['user', 'type', 'story', 'chapter', 'videofilename'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit)
                ->each(function ($item, $key) {
                    $relatedpersons = explode(',', $item['related_persons']);
                    $item['relatedpersons'] = model('app\admin\model\mox\inherit\Character')->where('id', 'in', $relatedpersons)->select();
                    $item['msg_num'] = model('app\admin\model\mox\play\Msg')->where('p_id', $item['id'])->count();
                });
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $params['user_id'] = $this->auth->user_id;
                $params['create_time'] = time();
                $this->model->save($params);
                // 处理相关人物
                if ($params['related_persons']) {
                    //获取刚刚添加的剧目的ID
                    $play_id = $this->model->id;
                    $related_persons = explode(',', $params['related_persons']);
                    $characters = model('app\admin\model\mox\inherit\Character')->where('id', 'in', $related_persons)->select();
                    foreach ($characters as $k => $v) {
                        $related_plays = explode(',', $v['related_plays']);
                        if (!in_array($play_id, $related_plays)) {
                            $related_plays[] = $play_id;
                        }
                        //去重
                        $related_plays = array_unique($related_plays);
                        $related_plays = implode(',', $related_plays);
                        model('app\admin\model\mox\inherit\Character')->where('id', $v['id'])->update(['related_plays' => $related_plays]);
                    }
                }
                $this->success();
            } else {
                $this->error();
            }
        }
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);

        //获取当前选中的剧目id
        $row_related_plays = explode(',', $row['related_persons']);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $params['user_id'] = $this->auth->user_id;
                $params['update_time'] = time();
                $this->model->save($params, ['id' => $ids]);
                // 处理相关人物
                if ($params['related_persons']) {
                    //获取刚刚添加的剧目的ID
                    $play_id = $ids;
                    //如果相关人物没有变化，则不处理
                    if ($row_related_plays == $params['related_persons']) {
                        return $this->success();
                    }
                    //获取row_related_plays和$params['related_persons']的差集
                    $diff = array_diff($row_related_plays, explode(',', $params['related_persons']));
                    //如果差集不为空，则删除差集中的剧目相关人物
                    if (!empty($diff)) {
                        $characters = model('app\admin\model\mox\inherit\Character')->where('id', 'in', $diff)->select();
                        foreach ($characters as $k => $v) {
                            $related_plays = explode(',', $v['related_plays']);
                            //如果剧目id不在人物相关剧目中，则添加
                            if (in_array($play_id, $related_plays)) {
                                unset($related_plays[array_search($play_id, $related_plays)]);
                            }
                            //去重
                            $related_plays = array_unique($related_plays);
                            $related_plays = implode(',', $related_plays);
                            model('app\admin\model\mox\inherit\Character')->where('id', $v['id'])->update(['related_plays' => $related_plays]);
                        }
                    }
                    //查询刚刚添加的人物id
                    $related_persons = explode(',', $params['related_persons']);
                    $characters = model('app\admin\model\mox\inherit\Character')->where('id', 'in', $related_persons)->select();
                    foreach ($characters as $k => $v) {
                        $related_plays = explode(',', $v['related_plays']);
                        if (!in_array($play_id, $related_plays)) {
                            $related_plays[] = $play_id;
                        }
                        //去重
                        $related_plays = array_unique($related_plays);
                        $related_plays = implode(',', $related_plays);
                        model('app\admin\model\mox\inherit\Character')->where('id', $v['id'])->update(['related_plays' => $related_plays]);
                    }
                }
                $this->success();
            } else {
                $this->error();
            }
        }

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        //获取剧目相关故事
        $row['story'] = model('app\admin\model\mox\inherit\story\Info')->where('id', $row['s_id'])->field('id, title,image')->find();
        //获取剧目相关章节
        $row['chapter'] = model('app\admin\model\mox\inherit\story\Chapter')->where('id', $row['c_id'])->field('id, title')->find();
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    model('app\admin\model\mox\play\Msg')->where('p_id', $v['id'])->delete();
                    $count += $v->delete();
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            }
            $this->error(__('No rows were deleted'));
        }
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
}
